﻿using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Newtonsoft.Json.Linq;
using DidaManager.Models.JsonConvert;

namespace LiteDb
{
    // 监控端口
    public class  MonitorPort
    {
        public const string CollectionName = nameof(MonitorPort);
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public int GroupDeviceId { get; set; }
        public string Extra { get; set; } = string.Empty;
    }

    // 监控设备
    public class MonitorDevice
    {
        public const string CollectionName = nameof(MonitorDevice);
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public int MonitorPortId { get; set; }
        public string Extra { get; set; } = string.Empty;
    }

    // 监控变量
    public class MonitorVariant
    {
        public const string CollectionName = nameof(MonitorVariant);
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public int MonitorDeviceId { get; set; }
        public string Extra { get; set; } = string.Empty;
    }

    public class MonitorPortRepository
    {
        private readonly ILiteCollection<MonitorPort> _collection;
        private readonly ILiteCollection<MonitorDevice> _deviceCollection;
        private readonly ILiteCollection<MonitorVariant> _variantCollection;
        
        public MonitorPortRepository(LiteDatabase db)
        {
            _collection = db.GetCollection<MonitorPort>(MonitorPort.CollectionName);
            _deviceCollection = db.GetCollection<MonitorDevice>(MonitorDevice.CollectionName);
            _variantCollection = db.GetCollection<MonitorVariant>(MonitorVariant.CollectionName);
        }

        public object Insert(object param)
        {
            try
            {
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                MonitorPort port = new MonitorPort();
                port.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                port.GroupDeviceId = jObject.TryGetValue("group_device_id", out var groupDeviceIdToken) ? groupDeviceIdToken.Value<int>() : 0;
                port.Extra = jsonString;
                
                // 检查在同一个分组设备下是否已存在相同名称的端口
                var existingPort = _collection.FindOne(p => p.GroupDeviceId == port.GroupDeviceId && p.Name == port.Name);
                if (existingPort != null)
                {
                    return ApiResponse.Fail("插入失败: 该分组设备下已存在同名端口");
                }
                
                port.Id = _collection.Insert(port);
                jObject["id"] = port.Id;
                port.Extra = jObject.ToString();
                _collection.Update(port);// 需要重新id的字段

                return ApiResponse.Success(port.Extra, "插入成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("插入失败: " + ex.Message);
            }
        }
        public object FindById(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                var result = _collection.FindById(id);
                if (result == null)
                    return ApiResponse.Fail("未找到数据", null, ApiResponseCode.NotFound);
                return ApiResponse.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAll(object param)
        {
            try
            {
                List<MonitorPort> list;

                if (param != null)
                {
                    // 根据分组设备ID过滤端口  
                    int groupDeviceId = Convert.ToInt32(param);
                    list = _collection.Find(p => p.GroupDeviceId == groupDeviceId).ToList();
                    if (list.Count == 0)// 可能是导入的数据库
                    {
                        list = _collection.FindAll().ToList();
                    }
                }
                else
                {
                    // 如果没有传入参数，获取所有端口  
                    list = _collection.FindAll().ToList();
                }

                // 转换为JSON数组格式
                var objectArray = list.Select(p => new
                {
                    id = p.Id,
                    name = p.Name,
                    groupDeviceId = p.GroupDeviceId,
                    extra = p.Extra
                }).ToArray();
                
                // 序列化为JSON字符串然后反序列化为动态对象，确保返回纯JSON格式
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);

                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object Update(object param)
        {
            try
            {
                MonitorPort port = new MonitorPort();
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                // 解析ID
                if (!jObject.TryGetValue("id", out var idToken))
                {
                    return ApiResponse.Fail("更新失败: 缺少ID字段");
                }
                port.Id = idToken.Value<int>();
                port.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                port.GroupDeviceId = jObject.TryGetValue("group_device_id", out var groupDeviceIdToken) ? groupDeviceIdToken.Value<int>() : 0;
                port.Extra = jsonString;
                
                // 检查在同一个分组设备下是否已存在相同名称的端口（排除当前更新的记录）
                var existingPort = _collection.FindOne(p => p.GroupDeviceId == port.GroupDeviceId && p.Name == port.Name && p.Id != port.Id);
                if (existingPort != null)
                {
                    return ApiResponse.Fail("更新失败: 该分组设备下已存在同名端口");
                }
                
                bool ok = _collection.Update(port);
                return ok ? ApiResponse.Success(port.Extra, "更新成功") : ApiResponse.Fail("更新失败", ok);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("更新异常: " + ex.Message);
            }
        }
        public object Delete(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                
                // 先检查端口是否存在
                var port = _collection.FindById(id);
                if (port == null)
                {
                    return ApiResponse.Fail("删除失败: 端口不存在");
                }
                
                // 获取该端口下的所有设备
                var devicesInPort = _deviceCollection.Find(d => d.MonitorPortId == id).ToList();
                var deviceIds = devicesInPort.Select(d => d.Id).ToList();
                
                // 统计要删除的变量数量
                int variantCount = 0;
                if (deviceIds.Count > 0)
                {
                    // 批量删除所有设备下的变量
                    foreach (int deviceId in deviceIds)
                    {
                        var variantsToDelete = _variantCollection.Find(v => v.MonitorDeviceId == deviceId).ToList();
                        variantCount += variantsToDelete.Count;
                        if (variantsToDelete.Count > 0)
                        {
                            _variantCollection.DeleteMany(v => v.MonitorDeviceId == deviceId);
                        }
                    }
                    
                    // 批量删除设备
                    _deviceCollection.DeleteMany(d => d.MonitorPortId == id);
                }
                
                // 删除端口
                bool ok = _collection.Delete(id);
                
                if (ok)
                {
                    return ApiResponse.Success(ok, $"删除成功，同时删除了 {devicesInPort.Count} 个设备和 {variantCount} 个变量");
                }
                else
                {
                    return ApiResponse.Fail("删除失败: 端口删除失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("删除异常: " + ex.Message);
            }
        }
        public object GetByGroupId(object param)
        {
            try
            {
                int groupId = Convert.ToInt32(param);
                var list = _collection.FindAll().Where(p => p.GroupDeviceId == groupId).ToList();
                return ApiResponse.Success(list);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object GetBridgePortOptions(object param)
        {
            try
            {
                const string protoTypeBridgePort = "3014"; // 3014表示桥接端口类型  
                List<MonitorPort> list;
                list = _collection.FindAll().ToList();
                // 需要判断端口proto_type字段的类型为3014  
                List<string> protoTypeList = new List<string>();
                foreach (var item in list)
                {
                    var extra = JObject.Parse(item.Extra);
                    // 获取proto_type字段的值，类型是string  
                    var protoType = extra.TryGetValue("proto_type", out var protoTypeToken) ? protoTypeToken.Value<string>() : "";
                    if (protoType == protoTypeBridgePort)
                    {
                        // extra里还有一个extra对象，需要先获取
                        var extraExtra = extra.TryGetValue("extra", out var extraExtraToken) ? extraExtraToken?.Value<JObject>() : null;
                        if (extraExtra != null)
                        {
                            var port = extraExtra.TryGetValue("port", out var portToken) ? portToken?.Value<string>() : "";
                            if (!string.IsNullOrEmpty(port))
                            {
                                protoTypeList.Add(port);
                            }
                        }
                    }
                }
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(protoTypeList);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }

        public object GetAllMonitorPortAndDeviceNames(object param)
        {
            try
            {
                List<MonitorPort> portList = _collection.FindAll().ToList();
                List<object> ports = new List<object>();
                foreach (var port in portList)
                {
                    List<object> devices = new List<object>();
                    var deviceList = _deviceCollection.Find(d => d.MonitorPortId == port.Id).ToList();
                    foreach (var device in deviceList)
                    {
                        devices.Add(new { title = device.Name, key = device.Id.ToString(), children = new List<object>() });// 每个device需要加上title、key、children字段，title、key字段为device.Name， children为空
                    }
                    ports.Add(new { title = port.Name, key = port.Id.ToString(), children = devices });
                }
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(ports);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取当前硬件使用资源数量
        /// </summary>
        public int GetHardwareCount()
        {
            return _collection.Count();
        }
    }

    public class MonitorDeviceRepository
    {
        private readonly ILiteCollection<MonitorDevice> _collection;
        private readonly ILiteCollection<MonitorVariant> _variantCollection;
        
        public MonitorDeviceRepository(LiteDatabase db)
        {
            _collection = db.GetCollection<MonitorDevice>(MonitorDevice.CollectionName);
            _variantCollection = db.GetCollection<MonitorVariant>(MonitorVariant.CollectionName);
        }
        public object Insert(object param)
        {
            try
            {
                MonitorDevice device = new MonitorDevice();
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                device.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                device.MonitorPortId = jObject.TryGetValue("monitor_port_id", out var monitorPortIdToken) ? monitorPortIdToken.Value<int>() : 0;
                device.Extra = jsonString;
                
                // 检查在同一个端口下是否已存在相同名称的设备
                var existingDevice = _collection.FindOne(d => d.MonitorPortId == device.MonitorPortId && d.Name == device.Name);
                if (existingDevice != null)
                {
                    return ApiResponse.Fail("插入失败: 该端口下已存在同名设备");
                }
                
                device.Id = _collection.Insert(device);
                jObject["id"] = device.Id;
                jObject["monitor_port_id"] = device.MonitorPortId;
                device.Extra = jObject.ToString();
                _collection.Update(device);// 需要重新id的字段

                return ApiResponse.Success(device.Extra, "插入成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("插入失败: " + ex.Message);
            }
        }
        public object FindById(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                var result = _collection.FindById(id);
                if (result == null)
                    return ApiResponse.Fail("未找到数据", null, ApiResponseCode.NotFound);
                return ApiResponse.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAll(object param)
        {
            try
            {
                List<MonitorDevice> list;
                
                if (param != null)
                {
                    // 根据端口ID过滤设备
                    int portId = Convert.ToInt32(param);
                    list = _collection.Find(d => d.MonitorPortId == portId).ToList();
                }
                else
                {
                    // 如果没有传入参数，获取所有设备
                    list = _collection.FindAll().ToList();
                }
                
                // 转换为JSON数组格式
                var objectArray = list.Select(d => new
                {
                    id = d.Id,
                    name = d.Name,
                    monitorPortId = d.MonitorPortId,
                    extra = d.Extra
                }).ToArray();
                
                // 序列化为JSON字符串然后反序列化为动态对象，确保返回纯JSON格式
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);
                
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object Update(object param)
        {
            try
            {
                MonitorDevice device = new MonitorDevice();
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                // 解析ID
                if (!jObject.TryGetValue("id", out var idToken))
                {
                    return ApiResponse.Fail("更新失败: 缺少ID字段");
                }
                device.Id = idToken.Value<int>();
                device.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                device.MonitorPortId = jObject.TryGetValue("monitor_port_id", out var monitorPortIdToken) ? monitorPortIdToken.Value<int>() : 0;
                device.Extra = jsonString;
                
                // 检查在同一个端口下是否已存在相同名称的设备（排除当前更新的记录）
                var existingDevice = _collection.FindOne(d => d.MonitorPortId == device.MonitorPortId && d.Name == device.Name && d.Id != device.Id);
                if (existingDevice != null)
                {
                    return ApiResponse.Fail("更新失败: 该端口下已存在同名设备");
                }
                
                bool ok = _collection.Update(device);
                return ok ? ApiResponse.Success(device.Extra, "更新成功") : ApiResponse.Fail("更新失败", ok);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("更新异常: " + ex.Message);
            }
        }
        public object Delete(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                
                // 先检查设备是否存在
                var device = _collection.FindById(id);
                if (device == null)
                {
                    return ApiResponse.Fail("删除失败: 设备不存在");
                }
                
                // 获取该设备下的变量数量
                var variantCount = _variantCollection.Count(v => v.MonitorDeviceId == id);
                
                // 批量删除变量
                if (variantCount > 0)
                {
                    _variantCollection.DeleteMany(v => v.MonitorDeviceId == id);
                }
                
                // 删除设备
                bool ok = _collection.Delete(id);
                
                if (ok)
                {
                    return ApiResponse.Success(ok, $"删除成功，同时删除了 {variantCount} 个变量");
                }
                else
                {
                    return ApiResponse.Fail("删除失败: 设备删除失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("删除异常: " + ex.Message);
            }
        }
        public object GetByGroupId(object param)
        {
            try
            {
                int groupId = Convert.ToInt32(param);
                var list = _collection.FindAll().Where(d => d.MonitorPortId == groupId).ToList();
                // 将list转换为json字符串
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }       
        /// <summary>
        /// 获取当前硬件使用资源数量
        /// </summary>
        public int GetHardwareCount()
        {
            return _collection.Count();
        }
    }

    public class MonitorVariantRepository
    {
        private readonly ILiteCollection<MonitorVariant> _collection;
        public MonitorVariantRepository(LiteDatabase db) => _collection = db.GetCollection<MonitorVariant>(MonitorVariant.CollectionName);
        public object Insert(object param)
        {
            try
            {
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);
                
                MonitorVariant variant = new MonitorVariant();
                
                // 提取基本字段
                if (jObject.TryGetValue("name", out var nameToken))
                {
                    variant.Name = nameToken.ToString();
                }
                
                if (jObject.TryGetValue("monitor_device_id", out var monitorDeviceIdToken))
                {
                    variant.MonitorDeviceId = monitorDeviceIdToken.Value<int>();
                }
                
                // 检查在同一个设备下是否已存在相同名称的变量
                if (!string.IsNullOrEmpty(variant.Name))
                {
                    var existingVariant = _collection.FindOne(v => v.MonitorDeviceId == variant.MonitorDeviceId && v.Name == variant.Name);
                    if (existingVariant != null)
                    {
                        return ApiResponse.Fail("插入失败: 该设备下已存在同名变量");
                    }
                }
                
                // 将Extra对象转换为BsonDocument
                variant.Extra = jsonString;
                variant.Id = _collection.Insert(variant).AsInt32;
                jObject["id"] = variant.Id;
                variant.Extra = jObject.ToString();
                _collection.Update(variant);// 需要重新id的字段
                return ApiResponse.Success(variant.Extra, "插入成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("插入失败: " + ex.Message);
            }
        }

        public object InsertBatch(object param)
        {
            try
            {
                var jsonString = param.ToString()!;
                var jArray = JArray.Parse(jsonString);

                // 准备要插入的变量列表
                var variants = new List<MonitorVariant>();
                var duplicateNames = new HashSet<string>();
                var deviceVariantNames = new Dictionary<int, HashSet<string>>();

                // 第一遍遍历：检查重复和收集数据
                foreach (var item in jArray)
                {
                    var name = item["name"]?.ToString() ?? "";
                    var deviceId = item["monitor_device_id"]?.Value<int>() ?? 0;

                    // 检查设备ID下是否已存在该变量名
                    if (!deviceVariantNames.ContainsKey(deviceId))
                    {
                        deviceVariantNames[deviceId] = new HashSet<string>();
                        // 获取该设备下已存在的变量名
                        var existingVariants = _collection.Find(v => v.MonitorDeviceId == deviceId).ToList();
                        foreach (var existing in existingVariants)
                        {
                            deviceVariantNames[deviceId].Add(existing.Name);
                        }
                    }

                    // 检查重复
                    if (deviceVariantNames[deviceId].Contains(name))
                    {
                        duplicateNames.Add(name);
                        continue;
                    }

                    // 添加到当前批次的名称集合中
                    deviceVariantNames[deviceId].Add(name);

                    // 创建新的变量对象
                    var variant = new MonitorVariant
                    {
                        Name = name,
                        MonitorDeviceId = deviceId,
                        Extra = item.ToString()
                    };
                    variants.Add(variant);
                }

                // 如果有重复项，返回错误
                if (duplicateNames.Count > 0)
                {
                    return ApiResponse.Fail($"插入失败: 以下变量名在对应设备下已存在: {string.Join(", ", duplicateNames)}");
                }

                // 批量插入
                if (variants.Count > 0)
                {
                    // 执行批量插入
                    var insertedIds = _collection.InsertBulk(variants);

                    // 更新每个变量的Extra字段，加入ID
                    foreach (var variant in variants)
                    {
                        var jObject = JObject.Parse(variant.Extra);
                        jObject["id"] = variant.Id;
                        variant.Extra = jObject.ToString();
                        _collection.Update(variant);
                    }

                    return ApiResponse.Success($"成功插入 {variants.Count} 条记录");
                }

                return ApiResponse.Success("没有新记录需要插入");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("插入失败: " + ex.Message);
            }
        }

        public object FindById(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                var result = _collection.FindById(id);
                if (result == null)
                    return ApiResponse.Fail("未找到数据", null, ApiResponseCode.NotFound);
                return ApiResponse.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAll(object param)
        {
            try
            {
                List<MonitorVariant> list;
                
                if (param != null)
                {
                    // 根据设备ID过滤变量
                    int deviceId = Convert.ToInt32(param);
                    list = _collection.Find(v => v.MonitorDeviceId == deviceId).ToList();
                }
                else
                {
                    // 如果没有传入参数，获取所有变量
                    list = _collection.FindAll().ToList();
                }
                
                // 转换为JSON数组格式
                var objectArray = list.Select(v => new
                {
                    id = v.Id,
                    name = v.Name,
                    monitorDeviceId = v.MonitorDeviceId,
                    extra = v.Extra
                }).ToArray();
                
                // 序列化为JSON字符串
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);
                
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object Update(object param)
        {
            try
            {
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);
                
                // 解析ID
                if (!jObject.TryGetValue("id", out var idToken))
                {
                    return ApiResponse.Fail("更新失败: 缺少ID字段");
                }
                
                int id = idToken.Value<int>();
                
                // 获取现有记录
                var existingVariant = _collection.FindById(id);
                if (existingVariant == null)
                {
                    return ApiResponse.Fail("更新失败: 记录不存在");
                }
                
                // 更新基本字段
                if (jObject.TryGetValue("name", out var nameToken))
                {
                    existingVariant.Name = nameToken.ToString();
                }
                
                if (jObject.TryGetValue("monitor_device_id", out var monitorDeviceIdToken))
                {
                    existingVariant.MonitorDeviceId = monitorDeviceIdToken.Value<int>();
                }
                
                // 检查在同一个设备下是否已存在相同名称的变量（排除当前更新的记录）
                if (!string.IsNullOrEmpty(existingVariant.Name))
                {
                    var duplicateVariant = _collection.FindOne(v => v.MonitorDeviceId == existingVariant.MonitorDeviceId && v.Name == existingVariant.Name && v.Id != id);
                    if (duplicateVariant != null)
                    {
                        return ApiResponse.Fail("更新失败: 该设备下已存在同名变量");
                    }
                }
                                
                // 将Extra对象转换为BsonDocument
                existingVariant.Extra = jObject.ToString();
                
                bool ok = _collection.Update(existingVariant);
                return ok ? ApiResponse.Success(existingVariant.Extra, "更新成功") : ApiResponse.Fail("更新失败", ok);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("更新异常: " + ex.Message);
            }
        }
        public object Delete(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                bool ok = _collection.Delete(id);
                return ok ? ApiResponse.Success(ok, "删除成功") : ApiResponse.Fail("删除失败", ok);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("删除异常: " + ex.Message);
            }
        }
        public object GetByGroupId(object param)
        {
            try
            {
                int groupId = Convert.ToInt32(param);
                var list = _collection.FindAll().Where(v => v.MonitorDeviceId == groupId).ToList();
                // 将list转换为json字符串
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAllMqttFormatDevicesJson(object param)
        {
            try
            {
                if (param == null)
                {
                    return ApiResponse.Fail("查询失败: 参数不能为空");
                }
                List<MonitorVariant> list;

                // 根据设备ID过滤变量
                int deviceId = Convert.ToInt32(param);
                list = _collection.Find(v => v.MonitorDeviceId == deviceId).ToList();

                // 转换为JSON数组格式 ，需要解析extra字段，extra字段是一个json字符串，需要转换为object
                var objectArray = list.Select(v =>
                {
                    var extra = JObject.Parse(v.Extra);
                    var extraExtra = extra.TryGetValue("extra", out var extraExtraToken) ? extraExtraToken?.Value<JObject>() : null;
                    if (extraExtra == null)
                    {
                        return new object();
                    }
                    return new
                    {
                         id = v.Id,
                         name = v.Name,
                         type = extraExtra.TryGetValue("dataType", out var typeToken) ? typeToken.Value<string>() : "",
                         desc = extraExtra.TryGetValue("alias", out var descToken) ? descToken.Value<string>() : ""
                    };
                }).ToArray();
                
                // 序列化为JSON字符串
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);
                
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取当前硬件使用资源数量
        /// </summary>
        public int GetHardwareCount()
        {
            return _collection.Count();
        }
        
        public object ExportToExcel(object param)
        {
            try
            {
                if (param == null)
                {
                    return ApiResponse.Fail("导出失败: 参数不能为空");
                }
                int deviceId = Convert.ToInt32(param);
                var vars = _collection.Find(v => v.MonitorDeviceId == deviceId).ToList();
                //VarConfigToConfigFile.ExportToExcel(vars);
                return ApiResponse.Success("导出成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("导出失败: " + ex.Message);
            }
        }

    }
}